<template>
  <view class="page-container">
    <HeaderBar
		:titleColor="titleColor" :navBarBgc="headerBgc" :isFixed="true"
        title="交通出行"
    ></HeaderBar>
    <view class="content-container">
      <wd-swiper
          :list="swiperList"
          autoplay
          value-key="imgUrl"
          height="136"
      ></wd-swiper>
	  
      <view class="choice-container mt50 mb30">
        <view class="tabs-container">
          <view
              v-for="(tabItem, tabIndex) in tabList"
              :key="tabIndex"
              class="tab"
              @click="handleChoiceTab(tabIndex)"
          >
            <img v-show="tabIndex === tabActiveIndex" class="img" src="http://img.jowong.com/aba/2025-03-26/未命名 -1_11_1742951965378.png" />
            <text :class="['tab-title', tabIndex === tabActiveIndex ? 'active-tab-title' : '']">{{ tabItem }}</text>
          </view>
        </view>
        <!--    直通车    -->
		<view v-if="tabActiveIndex === 0">
			<view class="direct-car-container">
			  <wd-picker :columns="startColumns" v-model="queryData.param.departurePlace" use-default-slot>
				  <view class="to-city-container address pr40">
					<text class="form-go mr10" v-if="!queryData.param.departurePlace">上车地</text>
					<text class="form-city-name area mr10">{{queryData.param.departurePlace}}</text>
					<wd-icon name="fill-arrow-down " size="22px"></wd-icon>
				  </view>
			  </wd-picker>
			  
			  <wd-icon name="translate-bold" size="16px" color="#1b9c61" @click="swap"></wd-icon>
			  
			  <wd-picker :columns="endColumns" v-model="queryData.param.destination" use-default-slot>
				<view class="to-city-container address pl40">
					<text class="form-go mr10" v-if="!queryData.param.destination">目的地</text>
					<text class="to-city-container area mr10">{{queryData.param.destination}}</text>
					<wd-icon name="fill-arrow-down" size="22px" ></wd-icon>
				</view>
			  </wd-picker>
			</view>
			<!--   日期     -->
			<wd-calendar v-model="datevalue" :min-date="minDate" style="background-color: aqua;" @confirm="handleConfirm">
				<view class="calendar-container">
					<view class="date-detail-container">
						<view class="week" v-if="!queryData.param.time">时间</view>
						<view class="date">{{queryData.param.time}}</view>
					</view>
					<wd-icon name="calendar" size="22px" color="#1b9c61"></wd-icon>
				</view>
			</wd-calendar>
			<!--   搜索     --> 
			<view class="carbtn" @click="handleSearch">
				<text>搜索</text>
			</view>
			
		</view>
		
		<!--    包车    -->
		<view  v-if="tabActiveIndex === 1"> 
			<view class="direct-car-container">
				<wd-picker :columns="startColumns" v-model="queryData.param.departurePlace" use-default-slot>
				  <view class="form-city-container address pr40">
					<text class="form-go mr10" v-if="!queryData.param.departurePlace">上车地</text>
					<text class="form-city-name area mr10">{{queryData.param.departurePlace}}</text>
					<wd-icon name="fill-arrow-down " size="22px"></wd-icon>
				  </view>
				</wd-picker>
			  
			  <wd-icon name="translate-bold" size="16px" color="#1b9c61" @click="swap"></wd-icon>
			  
			  <wd-picker :columns="endColumns" v-model="queryData.param.destination" use-default-slot>
				<view class="to-city-container address pl40">
					<text class="form-go mr10" v-if="!queryData.param.destination">目的地</text>
					<text class="to-city-container area mr10">{{queryData.param.destination}}</text>
					<wd-icon name="fill-arrow-down" size="22px" ></wd-icon>
				</view>
			  </wd-picker>
			</view>
			<!--   日期     -->
			<wd-calendar v-model="datevalue" :min-date="minDate" @confirm="handleConfirm">
				<view class="calendar-container">
					<view class="date-detail-container">
						<view class="week" v-if="!queryData.param.time">时间</view>
						<view class="date">{{queryData.param.time}}</view>
					</view>
					<wd-icon name="calendar" size="22px" color="#1b9c61"></wd-icon>
				</view>
			</wd-calendar>
			<view class="carbtn" @click="handleSearch">
				<text>搜索</text>
			</view>
		</view>
		
		<!--    租车    -->
		<view  v-if="tabActiveIndex === 2">
			<view class="CarRental-container"> 
				<view class="form-items">
					<text class="label">姓名</text>
					<input class="input" v-model="rentCar.contactName" placeholder="请输入您的姓名" placeholder-style="color:#BFBFBF;font-size:14px;"/>
				</view> 
				<view class="form-items">
					<text class="label">联系方式</text>
					<input class="input" type="number" maxlength="11" v-model="rentCar.contactPhone"  placeholder="请输入您的电话" placeholder-style="color:#BFBFBF;font-size:14px;" />
				</view>
				<view class="form-item">
					<!-- <view class="cartype br" @click="handlecarModel">
						<text class="carlabel">可选车型</text>
						<wd-icon name="fill-arrow-down " size="22px"></wd-icon>
						<text class="">{{rentCar.carModelName}}</text>
					</view> --> 
					<view class="cartype">
						<text class="carlabel">车型</text> 
						<input class="pinput"  v-model="rentCar.carModelName" placeholder="请输入车型" placeholder-style="color:#BFBFBF;font-size:14px" />
					</view>
					<view class="cartype">
						<text class="carlabel">用车人数</text> 
						<input class="pinput" type="number" v-model="rentCar.vehicleNum" placeholder="请输入人数" placeholder-style="color:#BFBFBF;font-size:14px" />
					</view>
				</view>
				<view class="form-item"> 
					<view class="cartype br">
						<text class="carlabel">取车地点</text> 
						<input class="pinput" v-model="rentCar.pickUpLocation" placeholder="请输入地点" placeholder-style="color:#BFBFBF;font-size:14px" />
					</view>
					
					<!-- <view class="cartype" @click="onShowDatePicker">
						<text class="carlabel">用车时间</text>
						<wd-icon name="fill-arrow-down " size="22px"></wd-icon>
						<text class="vehicleTime">{{pickershow[0]}}</text>
					</view> -->
						<view class="cartype" > 
							<text class="carlabel">用车时间</text>
							<wd-calendar v-model="datevalue" :min-date="minDate" @confirm="handlerentConfirm">
								<view style="display: flex;">
									<wd-icon v-if="!rentCar.vehicleTime" name="fill-arrow-down " size="22px"></wd-icon>
									<view class="rentCarvehicleTime">{{vehicleTime}}</view>
								</view> 
							</wd-calendar> 
						</view>
						
				</view>
				<view class="form-textarea">
				  <text class="areatext">其他需求备注信息</text>
				  <textarea v-model="rentCar.memo" placeholder="请输入备注" placeholder-style="color:#BFBFBF;font-size:14px;" class="textarea-box"></textarea>
				</view> 
				<view class="carbtn" @click="handleSuccessPopup">
					<text>提交需求</text>
				</view>
			</view>
		</view> 
      </view>
	  <successfulPopup :showSuccessPopup="showSuccessPopup" @close="closeSuccessPopup"></successfulPopup>
	  <carModelPopup :showcarModel="showcarModel" :carModelData="carModelData" @close="closecarModel"></carModelPopup>
	  
      <view  v-if="tabActiveIndex !== 2">
      	<view class="module-img-container">
      	  <image class="img" src="http://img.jowong.com/aba/2025-03-27/tuijian 拷贝 2_1743046264712.png"></image>
      	</view>
      	<view class="car-list-container">
      	  <DirectCarItem :queryData="queryData.param"
			v-for="(item, index) in carList" 
			:key="index" 
			:carInfo="item" /> 
      	</view>
      </view>
	  <view style="width: 100%;"  v-if="tabActiveIndex === 2"> 
		<img style="width: 100%;height: 280rpx;" src="http://img.jowong.com/aba/2025-03-28/pic2_1743145566955.png" alt="">
	  </view>
    </view>
	<!-- <mx-date-picker :show="showPicker" :type="pickervaluetype" :value="pickervalue" :show-tips="true" :begin-text="'取车'" :end-text="'还车'" :show-seconds="true" @confirm="ed" @cancel="ed" /> -->
	  
  </view>
</template>

<script setup lang="ts">
	import {ref,reactive} from "vue";
    import {styleSettingContent} from "@/api/system";
	import {onLoad} from "@dcloudio/uni-app"; 
	import DirectCarItem from "@/trafficSubPack/components/directCarItem/index.vue";
	import HeaderBar from "@/trafficSubPack/components/headerBar/index.vue";
	import successfulPopup from "@/components/successfulPopup/index.vue"; 
	import carModelPopup from "@/components/carModelPopup/index.vue"; 
    import MxDatePicker from "@/components/mx-datepicker/mx-datepicker.vue"; 
    import {gettraffic,getStartAndEnd,carModelLst,rentCarOrder,getprice} from "@/trafficSubPack/api/trafficHome";
  
	const swiperList = ref([]);
	const queryData = reactive({
	  param: {
		carType: 1,
        recommendMark: 1,
        departurePlace: "",
        destination: "",
	    time:''
	  },
	  pageQuery: {
		pageNo: 1,
		pageSize: 10
	  }
	}) 
	
	const headerBgc = ref("transparent");
	const titleColor = ref("#2D2D2D"); 
	const minDate =Date.now() 
	const vehicleTime = ref('')
	const datevalue = ref(Date.now())
	type State = {
	  userId: Number;
	  contactName: string;//用户名字
	  userType: Number;//用户类型
	  contactPhone: Number;//用户电话
	  vehicleType:string;//用车类型
	  carModelId:string;//车型
	  carModelName:string;//车型名称
	  vehicleNum:Number;//用车人数
	  pickUpLocation:string;//取车地点
	  vehicleTime:string;//取车时间
	  type:Number;//订单类型
	  memo:string;//备注
	  status:0
	};
	
	const rentCar = ref<State>({
		userId:888,
		contactName:'',
		userType:0,
		contactPhone: '' as unknown as number,
		vehicleType:'',
		carModelId:'',
		carModelName:'',
		vehicleNum:'' as unknown as number,
		pickUpLocation:'',
		vehicleTime:'',
		type:3,
		memo:'',
	    status:0
		
	}) 
	onPageScroll((e) => { 
		if (e.scrollTop > 110) {
			headerBgc.value = "#A7C6AC";
			titleColor.value = "#fff";
		} else {
			headerBgc.value = "transparent";
			titleColor.value = "#2D2D2D";
		}
	})
	const pickervaluetype = 'rangetime'
	const showPicker = ref(false) 
	const pickervalue = ref([])
	const pickershow = ref([])

	const tabList = ref(["直通车", "包车", "租车"]);
	const tabActiveIndex = ref(0);
	const startColumns = ref([])
	const endColumns = ref([])
	const showSuccessPopup = ref(false);
	const showcarModel = ref(false);
	const carList = ref([])
	
	const onShowDatePicker = () => { 
		showPicker.value = true;
	};
	// const ed = (e) => {//选择
	// 	showPicker.value = false;
	// 	if(e) { 
	// 		rentCar.value.vehicleStartTime = e.value[0]+":00"
	// 		rentCar.value.vehicleEndTime = e.value[1]+":00"
	// 		pickervalue.value = e.value 
	// 		pickershow.value = e.value.map(date => {
	// 		  const d = new Date(date);
	// 		  const month = String(d.getMonth() + 1).padStart(2, "0"); // 获取月份（补0）
	// 		  const day = String(d.getDate()).padStart(2, "0"); // 获取日期（补0）
	// 		  return `${month}/${day}`;
	// 		});
	// 	}
	// };
	
	const searchScenicSpotTicketSetting = async () => { 
	  try {
	    const res = await styleSettingContent({codes:"TRAFFIC_BANNER"}); 
		console.log('asdfghjk',res);
		  swiperList.value = res.result.TRAFFIC_BANNER
	  } catch (error) {
	    console.log(error,'获取配置失败') }
	}
    const handleChoiceTab = (index) => {
		tabActiveIndex.value = index;
		queryData.param.departurePlace = ''
		queryData.param.destination = ''
		if(index == 0) queryData.param.carType = 1
		if(index == 1) queryData.param.carType = 2
		getTraffic()
		getMudidi()
		if(index == 2) queryData.param.carType = 3;rentCar.value.vehicleType = "3";rentCar.value.type = 3 
		
	};
  
	function handleConfirm(value) {  
		console.log(value);
		// 将时间戳转换为 Date 对象
		let date = new Date(value.value); 
		// 提取年、月、日，并格式化为 YYYY-MM-DD
		let year = date.getFullYear(); // 获取年份
		let month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
		let day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
	    queryData.param.time = `${year}-${month}-${day}`;
	}
	function handlerentConfirm({ value }) {  
		// 将时间戳转换为 Date 对象
		let date = new Date(value); 
		// 提取年、月、日，并格式化为 YYYY-MM-DD
		let year = date.getFullYear(); // 获取年份
		let month = String(date.getMonth() + 1).padStart(2, '0'); // 获取月份并补零
		let day = String(date.getDate()).padStart(2, '0'); // 获取日期并补零
		vehicleTime.value = `${year}-${month}-${day}`;
	    rentCar.value.vehicleTime = `${year}-${month}-${day}T00:00:00`;
	}
	
    onLoad(() => {
		searchScenicSpotTicketSetting()
		getTraffic()
		getMudidi()
		const dates = {
			type:'date',
			value:Date.now()
		}
		handleConfirm(dates)
	});
	
    // 出发地目的地查询
	const getMudidi = ()=>{ 
	    getStartAndEnd(queryData.param.carType).then(res=>{
        let {result} = res;
        startColumns.value = result.departurePlace
        endColumns.value = result.destination
	    })
	}	 
	// 热门推荐列表查询
	const getTraffic = ()=>{  
	  gettraffic(queryData).then(res=>{
      let {result} = res;
		carList.value = result.records
		// 加载所有价格
		loadPrices(); 
	  })
	}
	 // 获取最低价格并存储到 item 中
	    const loadPrices = async () => {
	      for (const item of carList.value) {
	        const queryData = reactive({
	          ids: [item.id],
	          type: 2,
	        });
	        try {
	          const res = await getprice(queryData);
	          item.price = res.result[0].price;
	        } catch (error) { 
	          item.price = ""; // 设置默认值
	        }
	      }
	    }; 
	
	const swap = () => {
		[queryData.param.departurePlace, queryData.param.destination] = [queryData.param.destination, queryData.param.departurePlace];
	};
  
	const valicarForm = () => {
		if (!queryData.param.departurePlace.trim()) {
		uni.showToast({ title: '请选择上车地', icon: 'none' });
		return false;
		}
		if (!queryData.param.destination.trim()) {
		uni.showToast({ title: '请选择目的地', icon: 'none' });
		return false;
		}
		if (!queryData.param.time.trim()) {
		uni.showToast({ title: '请选择日期', icon: 'none' });
		return false;
		}
		return true;
	}; 
	const handleSearch = () => {
		if (!valicarForm()) return;
		uni.navigateTo({
		  url:'/trafficSubPack/pages/directCar/directCarSearch?start='+queryData.param.departurePlace + '&end=' + queryData.param.destination+'&time=' + queryData.param.time+'&carType=' + queryData.param.carType,
		})
	};  
	
	const validateForm = () => {
		if (!rentCar.value.contactName.trim()) {
		uni.showToast({ title: '请输入用户名字', icon: 'none' });
		return false;
		}
		if (!rentCar.value.contactPhone) {
		uni.showToast({ title: '请输入联系方式', icon: 'none' });
		return false;
		} 
		if (!rentCar.value.pickUpLocation.trim()) {
		uni.showToast({ title: '请输入取车车地', icon: 'none' });
		return false;
		}
		if (!rentCar.value.carModelName) {
		uni.showToast({ title: '请选择车型', icon: 'none' });
		return false;
		}
		if (!rentCar.value.vehicleNum ) {
		uni.showToast({ title: '请输入人数', icon: 'none' });
		return false;
		}
		if (!rentCar.value.vehicleTime) {
		uni.showToast({ title: '请选择日期', icon: 'none' });
		return false;
		}
		return true;
	}; 
	const handleSuccessPopup =async () => {
		if (!validateForm()) return;  
		// uni.showLoading({ title: '提交中...' });
		await rentCarOrder(rentCar.value).then((data)=>{
			console.log(data);
			// if(res.success){ 
				showSuccessPopup.value = true;  
			// } else { 
			// }
		}).catch(error=>{
			uni.showToast({ title: '提交失败', icon: 'error' }); 
		})
	  
	};
	const closeSuccessPopup = () => {
		showSuccessPopup.value = false; 
	};
	
	const carModelData = ref([])
	const handlecarModel = () => {  
		carModelLst(queryData).then(res=>{ 
			carModelData.value = res.result
			showcarModel.value = true;  
		})
	};
	const closecarModel = (value) => {
		if(value) {
			rentCar.value.carModelId = value.id
			rentCar.value.carModelName = value.name 
		}
		showcarModel.value = false; 
	};

</script>

<style lang="scss" scoped>
  .page-container {
    width: 100%;
    min-height: 100vh;
    background: linear-gradient(180deg, rgba(223,232,213,1) 0%, rgba(237,240,223,1) 10%, rgba(237,240,223,1) 100%);
    .content-container {
      padding: 28rpx;
      .choice-container {
        width: auto;
        border-radius: 10.5rpx;
        overflow: hidden;
        background: #FFFFFF;
        .tabs-container {
          display: flex;
          align-items: center;
          justify-content: space-around;
          padding:0 19.5rpx 16rpx 19.5rpx;
          background: #1b9c61;
          .tab {
            position: relative;
            width: 236rpx;
            height: 82.5rpx;
            text-align: center;
            .img {
              position: absolute;
              left: 0;
              bottom: -32rpx;
              width: 100%;
              height: 100%;
            }
            .tab-title {
              position: absolute;
              top:44rpx;
              left: 0;
              width: 236rpx;
              text-align: center;
              color: #FFFFFF;
            }
            .active-tab-title {
              color: #AA5413;
              font-weight: bold;
            }
            .circle-img {
              position: absolute;
              width: 70rpx;
              height: 16rpx;
              bottom: -10rpx;
              left: 50%;
              margin-left: -35rpx;
            }
          }
        }
		.CarRental-container{ 
			.form-items {
				display: flex; 
				align-items: center;
				width: 90%;
				margin:20rpx 30rpx; 
				border-bottom: 1rpx solid #eee; 
				line-height: 80rpx;
			} 
		   .label {  
				width: 24%;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			} 
		
			.input { 
				width: 76%; 
				// border: 1rpx solid;
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;  
			} 
			.chiose{
				// border: 1rpx solid;
				width: 90%; 
				
			}
			.form-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 92%;
				margin: 30rpx; 
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee; 
				// line-height: 80rpx;
				.cartype{ 
					display: flex;
					align-items: center;
					width: 48%;
					.carlabel{ 
						width: 44%; 
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
					.pinput{
						text-align: center;
						width: 56%; 
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 32rpx;
						color: #333333;  
					}
					.rentCarvehicleTime{
						min-width: 100rpx;
					}
				}
				.br{
					border-right:1rpx solid #EEEEEE;
				}
			}
			
			.form-textarea {
			  margin: 30rpx;
			  padding: 20rpx;
			  border: 1px solid #ddd;
			  border-radius: 10rpx;
			}
			.areatext{
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 29rpx;
				color: #333333;
			}
			.input-box,
			.textarea-box {
			  width: 100%;
			  padding: 10rpx;
			  border-radius: 8rpx;
			}

			.textarea-box {
			  height: 100rpx;
			  resize: none;
			}
			
		}
        .direct-car-container {
          display: flex;
          align-items: center;
          width: auto;
          padding: 40rpx 0;
          margin: 0 30rpx;
          border-bottom: 1rpx solid #EEEEEE;
          .address { 
			  min-width: 260rpx; 
            .area {
              font-size: 36rpx;
              font-weight: bold;
              color: #333333;
            }
			.form-go{
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
			}
          }
		  
        }
        .calendar-container {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: auto;
          padding: 40rpx 0;
          margin: 0 30rpx;
          border-bottom: 1rpx solid #EEEEEE;
          .date-detail-container {
            display: flex;
            align-items: flex-end;
            .date {
              font-size: 36rpx;
              font-weight: bold;
              color: #333333;
            }
            .week {
              font-size: 32rpx;
			  font-weight: 500;
              margin-left: 4rpx;
              color: #333333;
            }
          }
        }
        .search-container {
          width: auto;
          padding: 40rpx 0;
          margin: 0 30rpx;
          :deep() {
            .custom-search-button {
              padding: 40.5rpx 289.5rpx;
              border-radius: 10.5rpx;
              font-size: 33rpx;
              color: #FDFFEB;
              letter-spacing: 8rpx;
              text-align: center;
              background: #1B9C61;
            }
          }
        }
      }
	  
	  .carbtn{
	    color: #fff;
	    text-align: center;
	    width:92%;
	    margin:40rpx 4%;
	    height: 92rpx; 
	    line-height: 92rpx;
	    background: #1B9C61;
	    border-radius: 10rpx;
	  }
      .module-img-container {
        width: 229rpx;
        height: 45rpx;
        padding: 43rpx 0 50rpx 0;
        .img {
          width: 100%;
          height: 100%;
          background-size: cover;
        }
      }
    }
  }
</style>
